﻿using AutoMapper;
using InitQ.Cache;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SkiaSharp;
using Smart.Admin.Domain.Common;
using Smart.Admin.Domain.Model.Config;
using Smart.Admin.Domain.Model.Const;
using Smart.Admin.Domain.Model.Entity;
using Smart.Admin.Domain.Model.Enum;
using Smart.Admin.Domain.Model.Request.Account;
using Smart.Admin.Domain.Model.Request.Store;
using Smart.Admin.Domain.Model.Response;
using Smart.Admin.Domain.Model.Response.Account;
using Smart.Admin.Domain.Model.Response.Store;
using Smart.Admin.Domain.Model.Response.Menu;
using Smart.Admin.Domain.Repository;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Smart.Admin.Domain.Model.Request.Employee;
using Smart.Admin.Domain.Model.Response.Employee;

namespace Smart.Admin.Domain.Service
{
    /// <summary>
    /// 门店服务
    /// </summary>
    public class StoreService: EmployeeExtensions
    {
        private readonly SmartAdminDbContext _context;
        private readonly ICacheService _redisService;
        private readonly IOptions<JwtOptions> _options;
        private readonly IMapper _mapper;
        public StoreService(SmartAdminDbContext context, ICacheService redisService, IOptions<JwtOptions> options, IMapper mapper)
        {
            _context = context;
            _redisService = redisService;
            _options = options;
            _mapper = mapper;
        }



        /// <summary>
        /// 分页查询门店列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<List<GetStoreResponse>>> GetStorePageList(GetStorePageListRequest request)
        {
            var response = new JsonResponse<List<GetStoreResponse>>();
            try
            {
                var query = _context.Store.AsNoTracking();
                query = query.WhereIf(request.Status.HasValue, p => p.Status == request.Status);

                query = query.WhereIf(request.StartTime.HasValue, p => p.CreateTime >= request.StartTime);
                query = query.WhereIf(request.EndTime.HasValue, p => p.CreateTime <= request.EndTime);

                query = query.WhereIf(!string.IsNullOrEmpty(request.Keyword), p => p.StoreName.Contains(request.Keyword) || p.UserName.Contains(request.Keyword) || p.Phone.Contains(request.Keyword));
                query = query.Distinct();
                var data = await query.OrderByDescending(m => m.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToListAsync();


                response.code = "0";
                response.data = _mapper.Map<List<GetStoreResponse>>(data);
                response.total = await query.CountAsync();
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<List<GetStoreResponse>>(message: "系统错误");
            }
        }


        /// <summary>
        /// 查询门店信息
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<GetStoreResponse>> GetStoreInfo(long storeId)
        {
            var response = new JsonResponse<GetStoreResponse>();
            try
            {
                var model = await _context.Store.AsNoTracking().FirstOrDefaultAsync(m=>m.Id == storeId);
                if(model == null) return JsonResult.Error<GetStoreResponse>(message: "数据不存在");
                response.code = "0";
                response.data = _mapper.Map<GetStoreResponse>(model);
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<GetStoreResponse>(message: "系统错误");
            }
        }

        /// <summary>
        /// 创建门店
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> CreateStore(CreateStoreRequest request) 
        {
            try
            {
                if(request ==null) return JsonResult.Error(message: "参数错误");
                var bl = await _context.Store.AnyAsync(m => m.StoreName == request.StoreName);
                if (bl) return JsonResult.Error(message:"门店名称已存在");
                var model = _mapper.Map<StoreEntity>(request);
                model.CreateUserId = Convert.ToInt64(EmployeeId);
                model.UpdateUserId = Convert.ToInt64(EmployeeId);
                model.CreateTime = DateTime.Now;
                model.UpdateTime = model.CreateTime;
                await _context.Store.AddAsync(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }


        /// <summary>
        /// 修改门店
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> UpdateStore(UpdateStoreRequest request)
        {
            try
            {
                if (request == null) return JsonResult.Error(message: "参数错误");
                var model = await _context.Store.FirstOrDefaultAsync(m => m.Id == request.StoreId);
                if (model == null) return JsonResult.Error(message:"数据不存在");
                var bl = await _context.Store.AnyAsync(m => m.StoreName == request.StoreName && m.Id != request.StoreId);
                if (bl) return JsonResult.Error(message:"门店名称已存在");


                model.Status = request.Status;
                model.StoreName = request.StoreName;
                model.Address = request.Address;
                model.Remark = request.Remark;
                model.UpdateTime = DateTime.Now;
                model.UpdateUserId= Convert.ToInt64(EmployeeId);
                model.Pic = request.Pic;
                _context.Store.Update(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        /// <summary>
        /// 修改门店状态
        /// </summary>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public async Task<JsonResponse> UpdateStoreStatus(UpdateStoreStatusRequest request)
        {
            try
            {
                if(request == null || request.StoreIdList == null || request.StoreIdList.Count == 0) return JsonResult.Error(message: "参数错误");
                var list = await _context.Store.Where(m => request.StoreIdList.Contains(m.Id)).ToListAsync();
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        item.Status = request.Status;
                    }
                    _context.Store.UpdateRange(list);
                    await _context.SaveChangesAsync();
                }
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

    }
}
